#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#include "query.h"

int get_results(char *search, char *res_page){
	char *page = malloc(10000);
	unsigned long page_size;

	do{
		page_size = get_query(search, page);
	}while(page_size < 1000);

	int c = 700; //skip the first c chars
	int u = 0; 
	int i = 0; 
	int title_tag = 0;
	int titlepast_tag = 0;
	int link_tag = 0;
	int linkpast_tag = 0;
	
	struct {
		char title[100];
		char link[12];	
	} ent[20] = {0};

	while(*(page+c) != '\0'){
		
		if(*(page+c) == '<'){
			switch(*(page+c+1)){
			
				case 't':
				title_tag = 1;
				break;

				case 'l':
				link_tag = 1;
				break;
				
				case '/':
				if(*(page+c+2) == 't' || *(page+c+2) == 'l'){
					i=0;
					if(title_tag){
						title_tag = 0;
						titlepast_tag = 0;
					}else{
						link_tag = 0;
						linkpast_tag = 0;
						u++;
					}
				}
			}
		
		}
		
		if(title_tag){
			if(*(page+c-2) == 'e' && *(page+c-1) == '>')
				titlepast_tag = 1;
			if(titlepast_tag){
				ent[u].title[i] = *(page+c);
				i++;
			}
		}
		

		if(link_tag){
			if(*(page+c-2) == 'v' && *(page+c-1) == '=')
				linkpast_tag = 1;
			if(linkpast_tag){
				ent[u].link[i] = *(page+c);
				i++;
			}
		}
			
		c++;

	}
	char *temp = malloc(150);
	int sub_size = sizeof(char[15]);
	
	strcpy(res_page, "<html><body>");
	for(int x=0; x<20; x++){
		sub_size += snprintf(temp, sizeof(char[150]), "<a href=/watch?v=%s>%s</a><br>", ent[x].link, ent[x].title);
		strncat(res_page, temp, sizeof(res_page) - sub_size);	
	}
	strncat(res_page, "</body></html>", sizeof(res_page) - sub_size);
	
	free(page);
	return 0;
}
